const util = require('../../utils/util.js')//引入外部文件
const app = getApp()
Page({
  data: {
    api: app.globalData.api,
    product: [],//购物车
    total: 0,
    name: '',
    mobile: '',
    address: ''
  },
  onLoad: function (options) {
    this.data.name = wx.getStorageSync('name');
    this.data.mobile = wx.getStorageSync('mobile');
    this.data.address = wx.getStorageSync('address');
    this.data.product = util.getStorageCart('cart', 'id', 'count');
    this.data.total = 0;
    for (var i in this.data.product) {
      this.data.product[i].fee = this.data.product[i].price * this.data.product[i].count;
      this.data.total += this.data.product[i].fee;
    }
    this.setData(this.data);
  },
  onTabItemTap: function () {
    this.onLoad();
  },
  addCart: function (e) {
    var item = e.currentTarget.dataset.item;
    var len = util.enableAddStorageObj('cart', 'id', 'num', item, function () {
      util.alert(item.product + '买完了');
    })
    util.setTabBarBadgeNumber(1, len);
    this.onLoad();
  },
  reduceCart: function (e) {
    var item = e.currentTarget.dataset.item;
    var len = util.delStorageObj('cart', 'id', item.id);
    util.setTabBarBadgeNumber(1, len);
    this.onLoad();
  },
  onInput: function (e) {
    //util.alert(e.currentTarget.dataset.name);
    //util.alert(e.detail.value);
    this.data[e.currentTarget.dataset.name] = e.detail.value;
  },
  submit: function () {
    //util.alert(this.data.name+','+this.data.mobile+','+this.data.address);
    util.httpPost('/wx/order', {
      name: this.data.name,
      mobile: this.data.mobile,
      address: this.data.address,
      total: this.data.total,
      json: JSON.stringify(this.data.product)
    }, response => {
      if (response.code == 1) {
        //本地缓存
        wx.setStorageSync('name', this.data.name);
        wx.setStorageSync('mobile', this.data.mobile);
        wx.setStorageSync('address', this.data.address);
        wx.setStorageSync('cart', '');
        util.setTabBarBadgeNumber(1, 0);
        this.data.total = 0;
        this.onLoad();
      } else {
        util.alert(response.msg);
      }
    });

  }
})